package g14.sc12project.milestone1.Common;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLParser {

	static Logger log = Logger.getLogger(Utils.class.getName());

	// XML file read variable
	private DocumentBuilderFactory factory;
	private DocumentBuilder parser;
	private Document doc;
	private XPathExpression expr;

	/**
	 * Load xml doc.
	 * 
	 * @param xmlFileName
	 *            the xml file name
	 */
	public Document loadXMLDoc(String xmlFileName) {
		try {
			factory = DocumentBuilderFactory.newInstance();
			parser = factory.newDocumentBuilder();

			if (FileOrDirectoryExists(xmlFileName)) {
				doc = parser.parse(new File(xmlFileName));
			} else {
				doc = null;
				log.error(Constants.XML_FILE_NOT_FOUND);
			}

		} catch (Exception exp) {
			log.error(exp.getMessage());
		}

		return doc;

	}

	public boolean FileOrDirectoryExists(String fileOrDirectoryPath) {
		File fileData = new File(fileOrDirectoryPath);

		if (!fileData.isFile())
			return false;

		return true;
	}

	public NodeList getNodesByQuery(Document xmlDoc, String selectQuery) {
		NodeList nodes = null;
		try {
			// Create a XPathFactory
			XPathFactory xFactory = XPathFactory.newInstance();

			// Create a XPath object
			XPath xpath = xFactory.newXPath();

			// Compile the XPath expression
			expr = xpath.compile(selectQuery);

			// Run the query and get a nodeset
			Object result = expr.evaluate(doc, XPathConstants.NODESET);

			// Cast the result to a DOM NodeList
			nodes = (NodeList) result;
		} catch (Exception exp) {
			log.error(exp.getMessage());
		}

		return nodes;
	}
	
	public NodeList getAllNodesByTagName(Document xmlDoc, String nodeName) {
		NodeList nodes = null;
		try {
			nodes = xmlDoc.getElementsByTagName(nodeName);
		} catch (Exception exp) {
			log.error(exp.getMessage());
		}

		return nodes;
	}

}
